﻿using System;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using SleepManagement.Domains;

namespace SleepManagement.Controllers
{
    public interface ISleepManager
    {
        DreamBounds ReadDreamValues();
        void CheckInput(ref DreamBounds dreamBounds);

        void DoWork(DreamBounds bounds);
        bool IsTimeElapsed(DreamBounds bounds);
    }

    public class SleepManager : ISleepManager
    {
        private const string xmlName = "settings.xml";
        private IAnnoyingManager annoyingManager;

        public SleepManager(IAnnoyingManager annoyingManager)
        {
            if (annoyingManager == null)
                throw new ArgumentNullException("annoyingManager");
            this.annoyingManager = annoyingManager;
        }

        public DreamBounds ReadDreamValues()
        {
            try
            {
                return Serializator.FromFileToModel<DreamBounds>(Path.Combine(Application.StartupPath, xmlName));
            }
            catch (Exception)
            {
                return null;
            }
        }

        public void CheckInput(ref DreamBounds dreamBounds)
        {
            if (dreamBounds == null ||
                (dreamBounds.DreamBegin.TimeOfDay.Hours < 20 || dreamBounds.DreamEnd.TimeOfDay.Hours > 9 ||
                 dreamBounds.DreamEnd.TimeOfDay.Hours < 4))
            {
                dreamBounds = new DreamBounds();
                File.Delete(xmlName);
                dreamBounds.ModelToFile(xmlName);
            }
        }

        public void DoWork(DreamBounds bounds)
        {
            while (true)
            {
                Thread.Sleep(5000);
                annoyingManager.Process();
                if (IsTimeElapsed(bounds))
                    MessageBox.Show(DateTime.Now.ToString(CultureInfo.InvariantCulture));
                
                //annoyingManager.Process();
                //Process.Start("shutdown", "/h");
                // 
                // 				var stream = File.Open("D:\\1.txt", FileMode.Append);
                // 				byte[] buffer = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
                // 				stream.Write(buffer, 0, buffer.Length);
                // 				stream.Flush();
                // 				stream.Close();
            }
        }

        public bool IsTimeElapsed(DreamBounds bounds)
        {
            var now = DateTime.Now.TimeOfDay;
            return (now > bounds.DreamBegin.TimeOfDay || now < bounds.DreamEnd.TimeOfDay);
        }
    }
}
